/**
 * This file is a part of qloudgen-sec. 
 * You can redistribute qloudgen-sec and/or modify it under the terms of the Lesser GNU General Public License version 3. 
 * qloudgen-sec is distributed WITHOUT ANY WARRANTY. 
 *
 * See the Lesser GNU General Public License for more details at http://www.gnu.org/licenses/. 
 **/
package org.qloudgen.sec.jetty.nosql;

import java.util.Map;
import java.util.Collection;

import org.eclipse.jetty.server.Server;

import org.qloudgen.sec.cache.Cache;
import org.qloudgen.sec.cache.CacheManager;

/**
 * <p>Title: Cached session id support</p>
 * <p>Description: Single map for cached session id manager for jetty cluster implementation.</p>
 * <p>Copyright: qloudgen/sec 2014</p>
 * @author <a href="mailto:hyq.dd.sun@gmail.com">glue.3M</a>
 */
public class CachedSessionIdManager extends AbstractCachedSessionIdManager {
	/**
	 * Session cache name.
	 */
	private final static String DEFAULT_SESSION_CACHE = "JETTY-SESSIONS";
	/**
	 * Cache name.
	 */
	protected String cacheName = null;
	/**
	 * Cache manager.
	 */
	protected CacheManager cacheManager = null;

	/**
	 * Custom constructor.
	 *
	 * @param server
	 * @param cacheManager
	 */
	public CachedSessionIdManager(Server server , CacheManager cacheManager) {
		this( server , cacheManager , DEFAULT_SESSION_CACHE );
	}
	
	/**
	 * Custom constructor.
	 *
	 * @param server
	 * @param cacheManager
	 * @param cacheName
	 */
	public CachedSessionIdManager(Server server , CacheManager cacheManager , String cacheName) {
		//
		super( server );
		//
	    this.cacheManager = cacheManager;
	    this.cacheName = cacheName;
	}
	
	/**
	 * Returns all session.
	 *
	 * @return Collection
	 */
	protected Collection<String> getSessionIds() {
		Cache<String, Map> _sessions = cacheManager.getCache( cacheName );
		return _sessions.keys();
	}
	
	/**
	 * Returns current session.
	 *
	 * @param sessionId
	 * @return Map
	 */
	protected Map getSession(String sessionId) {
		Cache<String, Map> _sessions = cacheManager.getCache( cacheName );
		return _sessions.get( sessionId );
	}
	
	/**
	 * Removes current session.
	 *
	 * @param sessionId
	 * @return Map
	 */
	protected Map removeSession(String sessionId) {
		Cache<String, Map> _sessions = cacheManager.getCache( cacheName );
		return _sessions.remove( sessionId );
	}

	/**
	 * Returns current sessions.
	 *
	 * @return Cache<String, Map>
	 */
	public Cache<String, Map> getSessions() {
		return cacheManager.getCache( cacheName );
	}
}